package com.blue.rpc.client;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import com.blue.rpc.client.RpcClient;

public class RpcClientFactoryBean implements FactoryBean<Object>, InitializingBean
{
	private Class<?> interCls;
	private RpcClient rpcClient;
	private Object object;
	
	public RpcClientFactoryBean()
	{
	}
	
	public void setInterface(Class<?> interCls)
	{
		this.interCls = interCls;
	}

	public void setRpcClient(RpcClient rpcClient)
	{
		this.rpcClient = rpcClient;
	}

	@Override
	public Object getObject() throws Exception
	{
		return object;
	}

	@Override
	public void afterPropertiesSet() throws Exception
	{
		InvocationHandler handler = new RpcInvocationHandler(rpcClient);
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		object = Proxy.newProxyInstance(loader, new Class<?>[] {interCls}, handler);
	}

	@Override
	public Class<?> getObjectType()
	{
		return interCls;
	}

	@Override
	public boolean isSingleton()
	{
		return true;
	}
	
}
